package me.leiusual.sharing.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_main.*
import me.leiusual.sharing.R
import me.leiusual.sharing.ui.base.AbstractActivity
import me.leiusual.sharing.util.tool.Constants
import timber.log.Timber

/**
 * Create by leiusual on 2018/7/15
 */
class MainActivity : AbstractActivity(), IWXAPIEventHandler {

  companion object {
    fun intent(context: Context): Intent {
      return Intent(context, MainActivity::class.java)
    }
  }

  private val listener = NavController.OnDestinationChangedListener { _, destination, arguments ->
    Timber.v("destination = %s, arguments = %s", destination.label, arguments)
    bottom_navigation_view.visibility = when (destination.id) {
      R.id.homeHomeFragment,
      R.id.storeHomeFragment,
      R.id.cartHomeFragment,
      R.id.mineHomeFragment -> View.VISIBLE
      else -> View.GONE
    }
  }

  // 微信支付API
  private val api: IWXAPI by lazy {
    val api = WXAPIFactory.createWXAPI(applicationContext, Constants.WXPAY_APP_ID)
    api.registerApp(Constants.WXPAY_APP_ID)
    api
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)

    val navController = findNavController(R.id.nav_host_fragment)
    bottom_navigation_view.setupWithNavController(navController)
    navController.addOnDestinationChangedListener(listener)

    // 处理微信支付结果
    api.handleIntent(intent, this)
  }

  override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)

    // 处理微信支付结果
    setIntent(intent)
    api.handleIntent(intent, this)
  }

  override fun onDestroy() {
    super.onDestroy()

    findNavController(R.id.nav_host_fragment).removeOnDestinationChangedListener(listener)
  }

  override fun onReq(req: BaseReq) {
    Timber.v("onReq req = %s", req)
  }

  override fun onResp(resp: BaseResp) {
    Timber.v("onResp resp = %s", resp)

    // 发送广播
    val manager = LocalBroadcastManager.getInstance(this)
    manager.sendBroadcastSync(
        Intent(Constants.ACTION_WXPAY_RESULT)
            .putExtra("errCode", resp.errCode)
            .putExtra("errStr", resp.errStr)
    )
  }
}